﻿package com.finapps.stopspend.widget;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.finapps.stopspend.R;
import com.finapps.stopspend.entidades.SituacioActual;
import com.finapps.stopspend.serveis.SituacioActualService;
import com.finapps.stopspend.serveis.SituacioActualService.MetodeCalcul;

/**
 *
 * @author lujop        
 */
public class UpdateService extends Service
    implements Runnable
{
    private static AtomicBoolean running=new AtomicBoolean(false);
    private static SimpleDateFormat spd=new SimpleDateFormat("dd/MM/yyyy");
    private static int startId;
    private SharedPreferences valores;
    private SharedPreferences.Editor editor;

    private SituacioActualService situacioActualService=new SituacioActualService();
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {        
        handleOnStart(startId, intent);

        
        return START_NOT_STICKY;
    }

    private void handleOnStart(int startId, Intent intent) {
        Log.d("stopspending","puOnClickIntentInWidgetRemoteViewUpdate service starting");
     
        UpdateService.startId = startId;
        
        if (running.compareAndSet(false, true)) {
            new Thread(this).start();
        }        
    }

    @Override
    public void onStart(Intent intent, int startId) {
        //Metode onStart per versions < 2.0
        handleOnStart(startId, intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void run() {
        try {                          
           // while(true) {

                Log.i("STOP", "Threaaaaaaad");
            	valores = getSharedPreferences("valors", 0);
            	editor = valores.edit();
            	
                
                SituacioActual situacio=situacioActualService.calcularSituacioActual(Calendar.getInstance(),MetodeCalcul.MITJANA_MESOS);
                // guardar a la base de dades
                DecimalFormat df = new DecimalFormat("########0.00");

                editor.putString("SALDO", df.format(situacio.getSaldo()) + "€");
                editor.putString("ESTALVI", df.format(situacio.getEstalvi()) + "€");
                editor.putInt("COLOR", situacio.getColor().ordinal() + 1);
                
                editor.commit();
                /*
                ObjectiusDAO oDao = new ObjectiusDAO();

                
                for(Map.Entry<ObjetivoEntity, SituacioObjectiu> entry:situacio.getObjectius().entrySet()) {
                	ObjetivoEntity obj = entry.getKey();
                	obj.setColorSituacio(entry.getValue().getColorSituacio());
                	obj.setDinersFaltenTotal(entry.getValue().getDinersFaltenTotal());
                	oDao.saveObjectiu(obj);
                }
                */
                
                AppWidgetManager.getInstance(this).updateAppWidget(getAllWidgetsIds(),createRemoteView(situacio));              
                Thread.sleep(10000); //TODO: Canviar a Alarm manager per no monopolitzar device
				// També fora d'estat de provap pilot hauria d'actualitzar per push o menys sovint
           // }
            
            stopSelf(startId);
        } catch(InterruptedException e) { 
                Log.e("STOP","Update service INTERRUPTED");
        }finally {
        	Log.e("STOP","Update service END");
            running.set(false);
        }
    }

    private int[] getAllWidgetsIds() {
        List<Integer> ids=new ArrayList<Integer>();
        
                ComponentName component=new ComponentName(this,MainWidgetProvider.class);
                return AppWidgetManager.getInstance(this).getAppWidgetIds(component);
        }
    
    
        private RemoteViews createRemoteView(SituacioActual situacioActual) {
                
        	RemoteViews rv=new RemoteViews(getPackageName(), R.layout.main_widget);
            
                switch (situacioActual.getColor()) {
                case VERD:
                        rv.setImageViewResource(R.id.main_widget_semafor,R.drawable.verde);
                        break;
                case GROC:
                	rv=new RemoteViews(getPackageName(), R.layout.main_widget_naranja);
                        break;
                        
                case TARONJA:
                	rv=new RemoteViews(getPackageName(), R.layout.main_widget_naranja);
                        break;
                        
                case VERMELL:
                	rv=new RemoteViews(getPackageName(), R.layout.main_widget_rojo);
                        break;
                
                default:
                        throw new RuntimeException("Valor no esperat");
                }
                
                
                DecimalFormat df = new DecimalFormat("########0.00");
                
                
                rv.setTextViewText(R.id.main_widget_estalvi, df.format(situacioActual.getEstalvi())+"€");
                rv.setTextViewText(R.id.main_widget_saldo, df.format(situacioActual.getSaldo())+"€");
                int verde = getResources().getColor(R.color.iWish);
                rv.setTextColor(R.id.main_widget_saldo, verde);
                int soda = getResources().getColor(R.color.soda);
                rv.setTextColor(R.id.main_widget_estalvi, soda);
                
                return rv;
        }
}